package cn.easyplatform.studio.web.editors.project;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.biz.UpdateCmd;
import cn.easyplatform.studio.cmd.identity.GetAccessInfoCmd;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.AccessVo;
import cn.easyplatform.studio.vos.FieldVo;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.type.FieldType;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.*;

import java.util.ArrayList;
import java.util.List;

public class AccessEditor extends AbstractPanelEditor {
    private enum EditStatus {
        EDIT_CREATE, EDIT_CREATE_CHANGE, EDIT_SELECT, EDIT_SELECT_CHANGE
    }

    private Bandbox search;

    private Combobox category;

    private Listbox tables;

    private Toolbarbutton createBtn;

    private Toolbarbutton saveBtn;

    private Toolbarbutton deleteBtn;

    private Combobox chooseType;

    private Textbox code;

    private Textbox name;

    private EditStatus editStatus = EditStatus.EDIT_CREATE;

    private List<AccessVo> accessVos;

    private AccessVo selectAccess = new AccessVo();

    public AccessEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    protected void dispatch(Event evt) {
        Component c = evt.getTarget();
        if (evt.getTarget() instanceof Listitem) {
            final Listitem row = (Listitem) evt.getTarget();
            //列表行点击
            if (editStatus == AccessEditor.EditStatus.EDIT_SELECT_CHANGE || editStatus == AccessEditor.EditStatus.EDIT_CREATE_CHANGE)
                WebUtils.showConfirm(Labels.getLabel("button.save"), new EventListener<Event>() {
                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (event.getName().equals(Events.ON_OK))
                            Events.postEvent(new Event(Events.ON_CLICK, saveBtn));
                        else {
                            selectAccess = row.getValue();
                            editStatus = AccessEditor.EditStatus.EDIT_SELECT;
                            showHeaderBtns();
                            setValue();
                        }
                    }
                });
            else {
                selectAccess = row.getValue();
                editStatus = AccessEditor.EditStatus.EDIT_SELECT;
                showHeaderBtns();
                setValue();
            }
        } else if (evt.getTarget().getId().equals("access_combobox_category")) { //查询类别
            selectAccess = new AccessVo();
            setValue();
            search(category.getSelectedItem().getValue().toString(), search.getValue());
        } else if (c instanceof Bandbox) { //搜索框
            selectAccess = new AccessVo();
            setValue();
            String val = null;
            if (evt instanceof OpenEvent) {
                OpenEvent event = (OpenEvent) evt;
                val = (String) event.getValue();
                search.setValue(val);
            } else {
                val = search.getValue();
            }
            search(category.getSelectedItem().getValue().toString(), val);
        } else if (evt.getTarget() instanceof Textbox && evt.getName().equals(Events.ON_CHANGE)) {
            if (editStatus == EditStatus.EDIT_CREATE)
                editStatus = EditStatus.EDIT_CREATE_CHANGE;
            else if (editStatus == EditStatus.EDIT_SELECT)
                editStatus = EditStatus.EDIT_SELECT_CHANGE;
            showHeaderBtns();
        } else if (evt.getTarget().getId().equals("access_toolbarbutton_create")) {//新增按钮
            if (editStatus == EditStatus.EDIT_SELECT_CHANGE || editStatus == EditStatus.EDIT_CREATE_CHANGE)
                WebUtils.showConfirm(Labels.getLabel("button.save"), new EventListener<Event>() {
                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (event.getName().equals(Events.ON_OK))
                            Events.postEvent(new Event(Events.ON_CLICK, saveBtn));
                        else {
                            editStatus = EditStatus.EDIT_CREATE;
                            showHeaderBtns();
                            selectAccess = new AccessVo();
                            setValue();
                        }
                    }
                });
            else {
                editStatus = EditStatus.EDIT_CREATE;
                showHeaderBtns();
                selectAccess = new AccessVo();
                setValue();
            }
        } else if (evt.getTarget().getId().equals("access_toolbarbutton_save")) { //保存按钮

            if (Strings.isBlank(code.getValue())) {
                code.setFocus(true);
                throw new WrongValueException(code, Labels.getLabel(
                        "message.no.empty", new Object[]{Labels.getLabel("navi.entity")}));
            } else if (Strings.isBlank(chooseType.getValue())) {
                chooseType.setFocus(true);
                throw new WrongValueException(chooseType, Labels.getLabel(
                        "message.no.empty", new Object[]{Labels.getLabel("editor.access.title")}));
            } else if (selectAccess.getCode() == null) {
                setMessage();
                StringBuffer sqlBuffer = new StringBuffer("insert into sys_access_info(code,name,controlType) values (?,?,?)");
                List<FieldVo> sqlParams = new ArrayList<>();
                sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getCode()));
                sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getName()));
                sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getControlType()));
                Boolean upflag;
                try {
                    upflag = StudioApp.execute(new UpdateCmd(sqlBuffer.toString(), sqlParams));
                } catch (Exception e) {
                    WebUtils.showInfo(Labels.getLabel("message.code.exist"));
                    return;
                }
                if (upflag) {
                    WebUtils.showSuccess(Labels.getLabel("button.save"));
                    accessVos = StudioApp.execute(new GetAccessInfoCmd());
                    search(category.getSelectedItem().getValue().toString(), search.getValue());
                    code.setReadonly(true);
                    chooseType.setDisabled(true);
                    editStatus = EditStatus.EDIT_CREATE;
                    showHeaderBtns();
                } else {
                    selectAccess = new AccessVo();
                    WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("button.save")}));
                    return;
                }
            } else {
                setMessage();
                StringBuffer sqlBuffer = new StringBuffer("update sys_access_info set name=? where code=? and controlType=?");
                List<FieldVo> sqlParams = new ArrayList<>();
                sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getName()));
                sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getCode()));
                sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getControlType()));
                if (StudioApp.execute(new UpdateCmd(sqlBuffer.toString(), sqlParams))) {
                    WebUtils.showSuccess(Labels.getLabel("button.save"));
                    accessVos = StudioApp.execute(new GetAccessInfoCmd());
                    search(category.getSelectedItem().getValue().toString(), search.getValue());
                    editStatus = EditStatus.EDIT_SELECT;
                    showHeaderBtns();
                } else {
                    WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("button.save")}));
                }
            }
        } else if (evt.getTarget().getId().equals("access_toolbarbutton_delete")) { //删除按钮
            if (Strings.isBlank(selectAccess.getCode()) || Strings.isBlank(selectAccess.getControlType())) {
                WebUtils.showError(Labels.getLabel("editor.select",
                        new String[]{Labels.getLabel("navi.entity")}));
                return;
            }
            WebUtils.showConfirm(Labels.getLabel("button.delete"), new EventListener<Event>() {
                @Override
                public void onEvent(Event event) throws Exception {
                    if (event.getName().equals(Events.ON_OK)) {
                        String sqlstr = "delete from sys_access_info where code=? and controlType=?";
                        List<FieldVo> sqlParams = new ArrayList<>();
                        sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getCode()));
                        sqlParams.add(new FieldVo(FieldType.VARCHAR, selectAccess.getControlType()));
                        if (StudioApp.execute(new UpdateCmd(sqlstr, sqlParams))) {
                            getSelectedRow().detach();
                            accessVos = StudioApp.execute(new GetAccessInfoCmd());
                            search(category.getSelectedItem().getValue().toString(), search.getValue());
                            selectAccess = new AccessVo();
                            setValue();
                            editStatus = EditStatus.EDIT_CREATE;
                            showHeaderBtns();
                            WebUtils.showSuccess(Labels.getLabel("button.delete"));
                        }
                    }
                }
            });
        }
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.access"), "~./images/set.gif",
                "~./include/editor/project/access.zul");
        search = (Bandbox) is.getFellow("access_bandbox_search");
        search.addEventListener(Events.ON_OK, this);
        search.addEventListener(Events.ON_OPEN, this);
        category = (Combobox) is.getFellow("access_combobox_category");
        category.addEventListener(Events.ON_CHANGE, this);
        category.setSelectedIndex(0);
        category.setValue("All");
        tables = (Listbox) is.getFellow("access_listbox_tables");
        createBtn = (Toolbarbutton) is.getFellow("access_toolbarbutton_create");
        createBtn.addEventListener(Events.ON_CLICK, this);
        saveBtn = (Toolbarbutton) is.getFellow("access_toolbarbutton_save");
        saveBtn.addEventListener(Events.ON_CLICK, this);
        deleteBtn = (Toolbarbutton) is.getFellow("access_toolbarbutton_delete");
        deleteBtn.addEventListener(Events.ON_CLICK, this);
        chooseType = (Combobox) is.getFellow("access_combobox_type");
        chooseType.addEventListener(Events.ON_CHANGE, this);
        code = (Textbox) is.getFellow("access_textbox_code");
        code.addEventListener(Events.ON_CHANGE, this);
        name = (Textbox) is.getFellow("access_textbox_name");
        name.addEventListener(Events.ON_CHANGE, this);

        accessVos = StudioApp.execute(new GetAccessInfoCmd());
        createTables(accessVos);
        showHeaderBtns();
    }
    //ui
    //页面列表生成
    private void createTables(List<AccessVo> data) {
        List<Listitem> items = tables.getItems();
        for (AccessVo accessVo : data) {
            Listitem ti = new Listitem();
            ti.appendChild(new Listcell(accessVo.getCode()));
            ti.appendChild(new Listcell(accessVo.getName()));
            String typeString = "V".equals(accessVo.getControlType()) ?
                    Labels.getLabel("menu.access.visible") :Labels.getLabel("menu.access.disable");
            ti.appendChild(new Listcell(typeString));
            ti.setValue(accessVo);
            ti.addEventListener(Events.ON_CLICK, this);
            items.add(ti);
        }
    }

    private void showHeaderBtns() {
        if (editStatus == AccessEditor.EditStatus.EDIT_CREATE) {
            saveBtn.setDisabled(true);
            deleteBtn.setDisabled(true);
        } else if (editStatus == AccessEditor.EditStatus.EDIT_CREATE_CHANGE || editStatus == AccessEditor.EditStatus.EDIT_SELECT_CHANGE) {
            saveBtn.setDisabled(false);
            deleteBtn.setDisabled(true);
        } else if (editStatus == AccessEditor.EditStatus.EDIT_SELECT) {
            saveBtn.setDisabled(true);
            deleteBtn.setDisabled(false);
        }
    }

    //data
    private Listitem getSelectedRow() {
        if (selectAccess == null)
            return null;
        return tables.getSelectedItem();
    }
    //搜索
    private void search(String type, String val) {
        tables.getItems().removeAll(tables.getItems());
        List<AccessVo> accessVoList = new ArrayList<>();
        if (Strings.isBlank(type)) {
            if (Strings.isBlank(val)) {
                accessVoList = accessVos;
            } else {
                for (AccessVo accessVo : accessVos) {
                    if (accessVo.getCode().contains(val) || accessVo.getName().contains(val))
                        accessVoList.add(accessVo);
                }
            }
        } else {
            if (Strings.isBlank(val)) {
                for (AccessVo accessVo : accessVos) {
                    if (accessVo.getControlType().contains(type))
                        accessVoList.add(accessVo);
                }
            } else {
                for (AccessVo accessVo : accessVos) {
                    if (accessVo.getControlType().contains(type) &&
                            (accessVo.getCode().contains(val) || accessVo.getName().contains(val)))
                        accessVoList.add(accessVo);
                }
            }
        }

        createTables(accessVoList);
    }
    //页面输入框赋值
    private void setValue() {
        code.setReadonly(false);
        if (Strings.isBlank(selectAccess.getCode()) || Strings.isBlank(selectAccess.getControlType())) {
            code.setValue(null);
            code.setDisabled(false);
            name.setValue(null);
            chooseType.setValue(null);
            chooseType.setSelectedIndex(0);
            chooseType.setDisabled(false);
        } else {
            code.setValue(selectAccess.getCode());
            code.setDisabled(true);
            name.setValue(selectAccess.getName());

            if (Strings.isBlank(selectAccess.getControlType()) == false) {
                for (Comboitem ci : chooseType.getItems()) {
                    if (ci.getValue().equals(selectAccess.getControlType())) {
                        chooseType.setSelectedItem(ci);
                        break;
                    }
                }
            }
            chooseType.setDisabled(true);
        }
    }
    //获取页面输入框的值
    private void setMessage() {
        selectAccess.setCode(code.getValue());
        selectAccess.setName(name.getValue());
        if (chooseType.getSelectedItem() != null)
            selectAccess.setControlType(chooseType.getSelectedItem().getValue().toString());
    }
}
